﻿using AuthCenter.API.Application.Command.AccountRole;
using AuthCenter.Domain.Account;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace AuthCenter.API.Application.Handler.AccountRole
{
    public class CreateAccountRoleHandler : IRequestHandler<CreateAccountRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public CreateAccountRoleHandler(IBaseRepository<AccountModel> accountRepo,
                                        IBaseRepository<AccountRoleModel> accountroleRepo,
                                        IBaseRepository<RoleModel> roleRepo,
                                        IMapper mapper)
        {
            this.accountRepo = accountRepo;
            this.accountroleRepo = accountroleRepo;
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateAccountRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = accountroleRepo.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
            int r1 = 0;
            foreach (var item in res)
            {
                r1 = accountroleRepo.DeleteAsync(item).Result;
            }
            var list = request.AccountId.Split(',').Select(x=>Convert.ToInt64(x)).ToList();
            int r = 0;
            foreach (var item in list)
            {
                AccountRoleModel accountRole = new AccountRoleModel()
                {
                    Id = YitIdHelper.NextId(),
                    AccountId = item,
                    RoleId = request.RoleId
                };
               
               r = accountroleRepo.AddAsync(accountRole).Result;
            }
            if (r > 0)
            {
                result.Message = "分配员工成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "分配员工失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
